package dao;

import model.User;
import util.JdbcUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    /**
     * 根据用户名查找用户
     */
    public User findByUsername(String username) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT * FROM users WHERE username = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            rs = stmt.executeQuery();

            if (rs.next()) {
                return resultSetToUser(rs);
            }
            return null;

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            JdbcUtils.close(conn, stmt, rs);
        }
    }

    /**
     * 根据邮箱查找用户
     */
    public User findByEmail(String email) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT * FROM users WHERE email = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, email);
            rs = stmt.executeQuery();

            if (rs.next()) {
                return resultSetToUser(rs);
            }
            return null;

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            JdbcUtils.close(conn, stmt, rs);
        }
    }

    /**
     * 根据用户ID查找用户
     */
    public User findById(int userId) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT * FROM users WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, userId);
            rs = stmt.executeQuery();

            if (rs.next()) {
                return resultSetToUser(rs);
            }
            return null;

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } finally {
            JdbcUtils.close(conn, stmt, rs);
        }
    }

    /**
     * 插入新用户
     */
    public boolean insertUser(String username, String encryptedPassword, String email) {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "INSERT INTO users (username, password, email, created_at) VALUES (?, ?, ?, NOW())";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, encryptedPassword);
            stmt.setString(3, email);

            int rows = stmt.executeUpdate();
            return rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            JdbcUtils.close(conn, stmt);
        }
    }

    /**
     * 更新用户资料
     */
    public boolean updateProfile(int userId, String nickname, String email, String avatar) {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = JdbcUtils.getConnection();

            // 构建SQL语句，avatar为可选字段
            String sql;
            if (avatar != null && !avatar.trim().isEmpty()) {
                sql = "UPDATE users SET username = ?, email = ?, avatar = ? WHERE id = ?";
            } else {
                sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";
            }

            stmt = conn.prepareStatement(sql);
            stmt.setString(1, nickname);
            stmt.setString(2, email);

            if (avatar != null && !avatar.trim().isEmpty()) {
                stmt.setString(3, avatar);
                stmt.setInt(4, userId);
            } else {
                stmt.setInt(3, userId);
            }

            int rows = stmt.executeUpdate();
            return rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            JdbcUtils.close(conn, stmt);
        }
    }

    /**
     * 更新用户密码
     */
    public boolean updatePassword(int userId, String encryptedPassword) {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = JdbcUtils.getConnection();
            String sql = "UPDATE users SET password = ? WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, encryptedPassword);
            stmt.setInt(2, userId);

            int rows = stmt.executeUpdate();
            return rows > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            JdbcUtils.close(conn, stmt);
        }
    }

    /**
     * 获取所有用户
     */
    public List<User> findAll() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();

        try {
            conn = JdbcUtils.getConnection();
            String sql = "SELECT * FROM users ORDER BY created_at DESC";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();

            while (rs.next()) {
                users.add(resultSetToUser(rs));
            }
            return users;

        } catch (SQLException e) {
            e.printStackTrace();
            return users;
        } finally {
            JdbcUtils.close(conn, stmt, rs);
        }
    }

    /**
     * ResultSet 转 User 对象
     */
    private User resultSetToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setEmail(rs.getString("email"));
        user.setAvatar(rs.getString("avatar"));
        user.setRole(rs.getInt("role"));
        user.setStatus(rs.getInt("status"));
        user.setCreatedAt(rs.getTimestamp("created_at"));
        return user;
    }
}